<template>
  <div>
    <Space>
      <a-button type="primary" @click="openUploadModal">
        {{ title }}
      </a-button>
    </Space>
    <UploadModalManual v-bind="bindValue" :previewFileList="fileList" :fileListOpenDrag="fileListOpenDrag"
      :fileListDragOptions="fileListDragOptions" @register="registerUploadModal" @change="handleChange"
      @delete="handleDelete" />

    <UploadPreviewModalManual :value="fileList" @register="registerPreviewModal" @list-change="handlePreviewChange"
      @delete="handlePreviewDelete" />
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, unref, computed, useAttrs } from 'vue';
import { Recordable } from '@vben/types';
import { Space } from 'ant-design-vue';
import { useModal } from '@/components/Modal';
import { uploadContainerProps } from './props';
import { omit } from 'lodash-es';
import { isArray } from '@/utils/is';
import UploadModalManual from './components/uploadManual/UploadModalManual.vue';
import UploadPreviewModalManual from './components/uploadManual/UploadPreviewModalManual.vue';

defineOptions({ name: 'BasicUploadModal' });

const props = defineProps({ ...uploadContainerProps, title: { type: String, default: '' } });
const { title } = props;

const emit = defineEmits(['change', 'delete', 'preview-delete', 'update:value']);

const attrs = useAttrs();
// 上传modal
const [registerUploadModal, { openModal: openUploadModal }] = useModal();

//   预览modal
const [registerPreviewModal, { openModal: openPreviewModal }] = useModal();

const fileList = ref<string[]>([]);

const showPreview = computed(() => {
  const { emptyHidePreview } = props;
  if (!emptyHidePreview) return true;
  return emptyHidePreview ? fileList.value.length > 0 : true;
});

const bindValue = computed(() => {
  const value = { ...attrs, ...props };
  // console.log('bindvalue...', value);
  return omit(value, 'onChange');
});

watch(
  () => props.value,
  (value = []) => {
    fileList.value = isArray(value) ? value : [];
  },
  { immediate: true },
);

// 上传modal保存操作
function handleChange(urls: string[]) {
  fileList.value = [...unref(fileList), ...(urls || [])];
  emit('update:value', fileList.value);
  // emit('change', fileList.value);
}

// 预览modal保存操作
function handlePreviewChange(urls: string[]) {
  fileList.value = [...(urls || [])];
  emit('update:value', fileList.value);
  emit('change', fileList.value);
}

function handleDelete(record: Recordable<any>) {
  emit('delete', record);
}

function handlePreviewDelete(url: string) {
  emit('preview-delete', url);
}
</script>
